package com.lzb.browser.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class IconDownloadTask extends AsyncTask<String, Void, Bitmap> {

    private Context context;
    private OnIconDownloadListener listener;
    private String iconUrl;

    public interface OnIconDownloadListener {
        void onIconDownloaded(Bitmap bitmap, String iconUrl);
        void onIconDownloadFailed(String iconUrl);
    }

    public IconDownloadTask(Context context, OnIconDownloadListener listener) {
        this.context = context;
        this.listener = listener;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        if (params == null || params.length == 0) {
            return null;
        }
        
        iconUrl = params[0];
        if (TextUtils.isEmpty(iconUrl)) {
            return null;
        }
        
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        
        try {
            URL url = new URL(iconUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000); // 5秒连接超时
            connection.setReadTimeout(5000);  // 5秒读取超时
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                
                // 压缩图标到合适的大小（64x64）
                if (bitmap != null) {
                    bitmap = IconUtils.compressBitmap(bitmap, 64, 64);
                }
                
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (listener != null) {
            if (bitmap != null) {
                listener.onIconDownloaded(bitmap, iconUrl);
            } else {
                listener.onIconDownloadFailed(iconUrl);
            }
        }
    }
}